using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Nop.Services.Catalog;
using Nop.Core;
using Nop.Services.Topics;
using Nop.Core.ApiDataModel;
using Spotshub.Api.Filter;

namespace Spotshub.Api.Controllers.V1
{
    [ExceptionHandler]
    public class TopicController : ApiController
    {
        ITopicService _topicService;

        public TopicController(ITopicService topicService)
        {
            this._topicService = topicService;
        }


        // GET: api/topic/GetTopicBySystemName?systemName={name}
        public Nop.Core.ApiDataModel.TopicModel GetTopicBySystemName(string systemName)
        {
            Nop.Core.Domain.Topics.Topic topic = _topicService.GetTopicBySystemName(systemName);
            if (topic != null)
            {
                return new Nop.Core.ApiDataModel.TopicModel(topic.SystemName, topic.Title, topic.Body);
            }
            else
            {
                return null;
            }            
        }

		/// <summary>
		/// Get all api topics
		/// Need to run following sql script in db		
		/// </summary>
		/// <returns></returns>
		public IEnumerable<TopicModel> GetTopics()
		{
			/*
			 INSERT INTO [dbo].[Topic] 
			(
				[SystemName]
			   ,[IncludeInSitemap]
			   ,[IsPasswordProtected]
			   ,[Password]
			   ,[Title]
			   ,[Body]
			   ,[MetaKeywords]
			   ,[MetaDescription]
			   ,[MetaTitle]
			)
			SELECT 
				  'Api'+[SystemName]
				  ,[IncludeInSitemap]
				  ,[IsPasswordProtected]
				  ,[Password]
				  ,[Title]
				  ,[Body]
				  ,[MetaKeywords]
				  ,[MetaDescription]
				  ,[MetaTitle]
			  FROM [dbo].[Topic] WHERE SystemName NOT like 'Api%'
			 */
			var topics = _topicService.GetAllTopics();
			if(topics!=null)
				return topics.Where(t=>t.SystemName.StartsWith("api", StringComparison.OrdinalIgnoreCase)).Select(t => new TopicModel(t.SystemName, t.Title, t.Body));
			return null;
		}
    }
}
